package com.example.p2pinvest.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.alipay.sdk.app.PayTask;
import com.example.p2pinvest.R;
import com.example.p2pinvest.common.BaseActivity;
import com.example.p2pinvest.util.UIUtils;
import com.example.p2pinvest.util.pay.OrderInfoUtil2_0;
import com.example.p2pinvest.util.pay.PayResult;
import com.google.android.material.internal.TextWatcherAdapter;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ChongZhiActivity extends BaseActivity {

    /**
     * 支付宝支付业务：入参app_id
     */
    private static final String APPID = "";
    /**
     * RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE
     */
    public static final String RSA2_PRIVATE = "";
    private static final String RSA_PRIVATE = "";
    private static final int SDK_PAY_FLAG = 1;

    private Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == SDK_PAY_FLAG) {
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                /**
                 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                 */
                String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                String resultStatus = payResult.getResultStatus();
                // 判断resultStatus 为9000则代表支付成功
                if (TextUtils.equals(resultStatus, "9000")) {
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    UIUtils.toast("支付成功", false);
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    UIUtils.toast("支付失败", false);
                }
            }
        }
    };
    @BindView(R.id.iv_title_back)
    ImageView ivTitleBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_title_setting)
    ImageView ivTitleSetting;
    @BindView(R.id.chongzhi_text)
    TextView chongzhiText;
    @BindView(R.id.view)
    View view;
    @BindView(R.id.et_chongzhi)
    EditText etChongzhi;
    @BindView(R.id.chongzhi_text2)
    TextView chongzhiText2;
    @BindView(R.id.yue_tv)
    TextView yueTv;
    @BindView(R.id.btn_chongzhi)
    Button btnChongzhi;

    @Override
    protected void initData() {
        //默认情况下button不可操作
        btnChongzhi.setClickable(false);
        //改变button背景颜色
        btnChongzhi.setBackgroundResource(R.drawable.btn_02);

        etChongzhi.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                //当金额文本改变后,改变充值按钮的显示状态
                String money = etChongzhi.getText().toString();
                if (TextUtils.isEmpty(money)) {
                    //设置button为不可操作
                    btnChongzhi.setClickable(false);
                    //改变button背景颜色
                    btnChongzhi.setBackgroundResource(R.drawable.btn_02);
                } else {
                    //设置button为可操作
                    btnChongzhi.setClickable(true);
                    //改变button背景颜色
                    btnChongzhi.setBackgroundResource(R.drawable.btn_01);
                }
            }
        });
    }

    @Override
    protected void initTitle() {
        tvTitle.setText("充值");
        ivTitleBack.setVisibility(View.VISIBLE);
        ivTitleSetting.setVisibility(View.INVISIBLE);
    }

    @OnClick(R.id.iv_title_back)
    public void back(View view) {
        this.removeCurrentActivity();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_chong_zhi;
    }

    @OnClick(R.id.btn_chongzhi)
    public void chongzhi(View view) {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                            //
                            finish();
                        }
                    }).show();
            return;
        }
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        new Thread(() -> {
            PayTask alipay = new PayTask(ChongZhiActivity.this);
            Map<String, String> result = alipay.payV2(orderInfo, true);
            Log.i("msp", result.toString());

            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;

            mHandler.sendMessage(msg);
        }).start();
    }
}